package com.theta.common.base.swagger.doc.core.executor;

import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;

import com.github.xiaoymin.knife4j.aggre.core.RouteExecutor;
import com.github.xiaoymin.knife4j.aggre.core.RouteRequestContext;
import com.github.xiaoymin.knife4j.aggre.core.RouteResponse;
import com.github.xiaoymin.knife4j.aggre.core.executor.DefaultClientResponse;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RestTemplateRouteExecutor implements RouteExecutor {

	
	private RestTemplate restTemplate;
	
	public RestTemplateRouteExecutor(RestTemplate restTemplate) {
		this.restTemplate=restTemplate;
	}
	
	@Override
	public RouteResponse executor(RouteRequestContext routeContext) {
		RouteResponse routeResponse=null;
		try {
			log.info("start request: {}",routeContext.getUrl());
			HttpMethod method=HttpMethod.valueOf(routeContext.getMethod());
//			RequestCallback requestCallback=client->{
//				client.getBody().write(routeContext.getRequestContent().);
//			}
//			this.restTemplate.execute(routeContext.getUrl(), method, requestCallback, responseExtractor)
			ResponseEntity<Object> resp= restTemplate.getForEntity(routeContext.getUrl(), Object.class);
			log.info("{},body:{}",resp.getStatusCode(),resp.getBody());
			routeResponse=new RestTemplateResponse(resp);
		} catch (Exception e) {
			log.error("",e);
            routeResponse=new DefaultClientResponse(routeContext.getOriginalUri(),e.getMessage());
		}
		return routeResponse;
	}

}
